package cn.fuxi2022.auth.service.impl;

import cn.fuxi2022.auth.properties.WeChatOpenConstantProperties;
import cn.fuxi2022.auth.service.UserLoginByWeChatOpenService;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.core.utils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Slf4j
@Service
public class UserLoginByWeChatOpenServiceImpl implements UserLoginByWeChatOpenService {
    @Override
    public HashMap<String, String> getOpenIdAndAccess(String code) {

        // 1.拼接三个参数 ：id  秘钥 和 code值
        String accessTokenUrl = String.format(
                BASE_ACCESS_TOKEN_URL,
                WeChatOpenConstantProperties.APP_ID,
                WeChatOpenConstantProperties.APP_SECRET,
                code
        );

        // 2.模拟浏览器发送请求，获取响应
        String accessTokenInfo;
        try {
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmartGroupException("微信登录失败");
        }

        //log.info(accessTokenInfo);

        // 3.解析响应，获取 access_token 和 openid
        JSONObject jsonObject = JSON.parseObject(accessTokenInfo);
        HashMap<String, String> map = new HashMap<>();
        map.put("openid", (String) jsonObject.get("openid"));
        map.put("access_token", (String) jsonObject.get("access_token"));
        map.put("unionid", (String) jsonObject.get("unionid"));
        return map;

    }

    @Override
    public HashMap<String, String> getUserInfo(String openid, String accessToken) {
        // 拼接两个参数
        String userInfoUrl = String.format(
                BASE_USER_INFO_URL,
                accessToken,
                openid
        );

        // 发送请求
        String userInfo;
        try {
            userInfo = HttpClientUtils.get(userInfoUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmartGroupException("微信获取信息失败");
        }

        // 3.获取 头像 和 昵称 和 性别
        JSONObject jsonObject = JSON.parseObject(userInfo);
        HashMap<String, String> map = new HashMap<>();
        map.put("nickname", String.valueOf(jsonObject.get("nickname")));
        map.put("sex", String.valueOf(jsonObject.get("sex")));
        map.put("headimgurl", String.valueOf(jsonObject.get("headimgurl")));
        map.put("openid", String.valueOf(jsonObject.get("openid")));
        map.put("unionid", String.valueOf(jsonObject.get("unionid")));
        return map;
    }
}
